Today you will
Build your own shop app: a real web page on top of the Module 6 database.
- Run a Streamlit app and explain what the local server does.
- Explain the rerun rule: the whole script runs again on every click.
- Use widgets to get values, and messages, tables and charts to show results.
- Build the shop app step by step on
shop_db, with a form that saves new products.
Deep dive A: from print() to a web page
You've watched a Streamlit app at the end of every module. Today you build one. Here's the Module 2 greeting, first as a normal program, then as an app:
name = input("What's your name? ")
print(f"Welcome to the bakery, {name}!")import streamlit as st
st.title("Mama J's Bakery")
name = st.text_input("What's your name?")
if name != "":
st.write(f"Welcome to the bakery, {name}!")See the browser: a title, "Mama J's Bakery", and a text box.
Type Jada and press Enter:
Welcome to the bakery, Jada!| Normal program | Streamlit app |
|---|---|
print() | st.write(), st.title(), st.success()... |
input() | st.text_input(), st.number_input(), st.selectbox()... |
| Answers appear in Thonny's shell | Answers appear on a web page |
| Run with the green Run button | Run with streamlit run hello_app.py in the system shell |
Deep dive B: the rerun rule
This is the one big idea of Streamlit. Run this and click the button a few times:
import streamlit as st
count = 0
if st.button("Add one"):
count += 1
st.write("Count:", count)Click Add one: Count: 1
Click Add one again: Count: 1
It never gets to 2.Every time you click a button, tick a box or change a number, Streamlit runs the whole script again, from the top. So count = 0 runs again every time, and the 1 from last time is wiped.
It's the same thing you saw in Module 6 when a program closes: variables don't remember. That's exactly why the shop app keeps its products and sales in shop.db. The database remembers between reruns.
| What you do | What Streamlit does |
|---|---|
| Open the app | Runs the script top to bottom |
| Click a button | Runs the whole script again. That button gives True, just this once |
| Change a number or tick a box | Runs the whole script again with the new value |
Deep dive C: widgets give you values
A widget is anything the user can type in, pick or click. Each one gives back a value you store in a variable, just like input() did.
| Widget | Gives back | Like... |
|---|---|---|
st.text_input("Name") | The text typed | input() |
st.number_input("How many?") | A number, no int() needed | int(input()) |
st.selectbox("Product", a_list) | The item picked from the list | Module 5 lists |
st.checkbox("Loyalty card") | True or False | Module 3 True/False |
st.button("Sell") | True only on the click | Deep dive B |
import streamlit as st
prices = {"Beef Patty": 5.00, "Cheese Patty": 5.00,
"Coconut Tart": 4.00, "Sorrel Drink": 3.50}
st.title("Price Checker")
item = st.selectbox("Product", list(prices))
qty = st.number_input("How many?", min_value=1, value=1, step=1)
member = st.checkbox("Loyalty card (10% off)")
total = prices[item] * qty
if member:
total = total * 0.90
st.metric("Total", f"EC${total:.2f}")See the browser. Pick Coconut Tart, set How many? to 3:
Total EC$12.00
Tick Loyalty card (10% off):
Total EC$10.80Deep dive D: messages and the Module 3 if
Streamlit has four coloured messages. Pick one with if / elif / else:
st.success()green: it workedst.info()blue: just so you knowst.warning()yellow: carefulst.error()red: something's wrong
import streamlit as st
import shop_db
shop_db.setup()
st.title("Stock Check")
for p in shop_db.get_products():
if p["stock"] == 0:
st.error(f"{p['name']}: SOLD OUT")
elif p["stock"] < 25:
st.warning(f"{p['name']}: only {p['stock']} left")
else:
st.success(f"{p['name']}: {p['stock']} in stock")See the browser (fresh shop):
Beef Patty: 40 in stock (green)
Cheese Patty: 30 in stock (green)
Coconut Tart: 25 in stock (green)
Sorrel Drink: only 20 left (yellow)Deep dive E: showing the shop's data
Three ways to show data, all straight from shop_db:
| Command | Shows | Give it |
|---|---|---|
st.dataframe() | A table you can scroll and sort | A list of dictionaries |
st.metric() | One big number with a label | A label and a value |
st.bar_chart() | A bar chart | The data, plus which column goes along (x) and up (y) |
import streamlit as st
import shop_db
shop_db.setup()
st.title("Sales")
st.dataframe(shop_db.get_products()) # a table
report = shop_db.sales_report()
total = 0
for row in report: # Module 4 running total
total += row["money"]
st.metric("Money taken", f"EC${total:.2f}") # one big number
if report: # only if there are sales
st.bar_chart(report, x="name", y="money") # a chart
else:
st.info("No sales yet - make a sale first.")See the browser, after selling 3 Beef Patty and 2 Coconut Tart:
A table of the 4 products and their stock
Money taken EC$23.00
A bar chart: Beef Patty 15, Coconut Tart 8
With no sales yet:
Money taken EC$0.00
No sales yet - make a sale first. (blue)Deep dive F: forms - fill in, then save
Normally every change reruns the app straight away. A form groups inputs together so nothing happens until you press its button. Perfect for adding a product: type the name, price and stock, then save once.
import streamlit as st
import shop_db
shop_db.setup()
st.title("Add a product")
with st.form("new_product"):
name = st.text_input("Product name")
price = st.number_input("Price (EC$)", min_value=0.0, step=0.50)
stock = st.number_input("Starting stock", min_value=0, step=1)
saved = st.form_submit_button("Save product")
if saved:
if name.strip() == "":
st.warning("Please type a product name.")
else:
st.success(shop_db.add_product(name.strip(), price, stock))
st.dataframe(shop_db.get_products())See the browser. Type Bread Pudding, price 6.00, stock 12, press Save product:
Added Bread Pudding.
The table below now has 5 products.
Press Save product again: Bread Pudding is already in the shop.
Leave the name empty and save: Please type a product name.with st.form("new_product"): means: everything indented under this line belongs to the form, the same way indented lines belong to an if or a for. st.form_submit_button() is the form's own button, and gives True when it's pressed.1. Demo: the finished shop app
This is what you're building today. Put it in the same folder as shop_db.py, then run streamlit run shop_app.py. It uses the same shop.db as Module 6, so your Module 6 sales show up here too.
# shop_app.py - Module 7: Mama J's shop app (the finished version)
# Run it with: streamlit run shop_app.py (shop_db.py in the same folder)
import streamlit as st
import shop_db
shop_db.setup()
st.sidebar.title("Mama J's Bakery")
st.sidebar.write("Open Mon-Sat, 7am - 6pm")
st.title("Shop App")
# ---- sell ----
st.header("Make a sale")
names = []
for p in shop_db.get_products():
names.append(p["name"])
choice = st.selectbox("Product", names)
qty = st.number_input("How many?", min_value=1, value=1, step=1)
if st.button("Sell"):
message = shop_db.record_sale(choice, qty)
if "Sold" in message:
st.success(message)
else:
st.error(message)
# ---- add a product ----
st.header("Add a product")
with st.form("new_product"):
name = st.text_input("Product name")
price = st.number_input("Price (EC$)", min_value=0.0, step=0.50)
stock = st.number_input("Starting stock", min_value=0, step=1)
saved = st.form_submit_button("Save product")
if saved:
if name.strip() == "":
st.warning("Please type a product name.")
else:
st.success(shop_db.add_product(name.strip(), price, stock))
# ---- stock ----
st.header("Stock")
st.dataframe(shop_db.get_products())
for p in shop_db.query("SELECT name, stock FROM products WHERE stock < 10"):
st.warning(f"Low stock: {p['name']} ({p['stock']} left)")
# ---- sales ----
st.header("Sales so far")
report = shop_db.sales_report()
if report:
total = 0
for row in report:
total += row["money"]
st.metric("Money taken", f"EC${total:.2f}")
st.bar_chart(report, x="name", y="money")
else:
st.info("No sales yet. Make one above!")See the browser:
Sidebar: Mama J's Bakery, Open Mon-Sat, 7am - 6pm
Make a sale: pick a product and a number, press Sell
Sold 2 x Coconut Tart = EC$8.00. 23 left. (green)
Try 99 of something: Only 25 Coconut Tart left. (red)
Add a product: the form from Deep dive F
Stock: the table, plus a yellow warning for anything under 10
Sales so far: Money taken, and a bar chart2. Build it yourself, step by step
Make a new file, my_shop_app.py. Run it after every step, so you always know which step broke something.
Step 1: title, sidebar and stock. Change the shop name and hours to your own.
# Step 1 - title, sidebar and the stock table
import streamlit as st
import shop_db
shop_db.setup()
st.sidebar.title("Mama J's Bakery")
st.sidebar.write("Open Mon-Sat, 7am - 6pm")
st.title("Shop App")
st.header("Stock")
st.dataframe(shop_db.get_products())Step 2: selling. Add this above st.header("Stock"), so the table updates after a sale.
st.header("Make a sale")
names = []
for p in shop_db.get_products():
names.append(p["name"])
choice = st.selectbox("Product", names)
qty = st.number_input("How many?", min_value=1, value=1, step=1)
if st.button("Sell"):
message = shop_db.record_sale(choice, qty)
if "Sold" in message:
st.success(message)
else:
st.error(message)Step 3: the sales report. Add this at the very bottom.
st.header("Sales so far")
report = shop_db.sales_report()
if report:
total = 0
for row in report:
total += row["money"]
st.metric("Money taken", f"EC${total:.2f}")
st.bar_chart(report, x="name", y="money")
else:
st.info("No sales yet. Make one above!")Step 4: the form. Copy the form from Deep dive F (from with st.form down) under the selling part.
Bug hunt
This app doesn't crash, but it's losing stock. Open it and change the number a few times without pressing Sell. Watch "Beef Patty left".
# BUG HUNT - this app doesn't crash, but it's losing stock!
# Open it, then change the number box a few times WITHOUT pressing Sell.
# Watch "Beef Patty left". Why does it go down? Fix it so it only sells on Sell.
import streamlit as st
import shop_db
shop_db.setup()
st.title("Quick Sell")
qty = st.number_input("How many Beef Patty?", min_value=1, value=1, step=1)
sell = st.button("Sell")
message = shop_db.record_sale("Beef Patty", qty)
if sell:
st.success(message)
st.write("Beef Patty left:", shop_db.find_product("Beef Patty")["stock"])Hints (open only if stuck)
- Remember Deep dive B: what runs every time you change the number?
- Which line actually sells the patty? Is it inside the if?
Words to know
| Word | Meaning |
|---|---|
| Streamlit | A Python package that turns a script into a web app |
| Local server | A small web server on your own computer (http://localhost:8501) |
| Rerun | Streamlit runs the whole script again on every click or change |
| Widget | Something the user types in, picks or clicks: text box, number box, button |
st.form | A group of inputs saved with one button |
st.metric | One big number with a label |
st.sidebar | The panel down the left side of the app |
Practice
Homework 7 (5%): one new feature
Add one feature to your shop app. Choose one:
Submit your .py file and a screenshot of it running, before the next module.
| Mark | Means |
|---|---|
| 5 | Runs and has everything |
| 3 | Runs with parts missing, or has errors |
| 1 | Started |
| 0 | Not submitted |
Quiz 7
Check yourself here, then take the graded quiz in the quiz section of robotics.a3tech.uk (two tries).
ADDITIONAL - STREAMLIT APP - SNEAK PEEK 7
Not every app is a shop. Same skills, different idea: a quiz. Next module you build an app about anything you like, and this is the kind of thing you could make.
# quiz_app.py - Module 7 sneak peek: a different kind of app, same skills
# Run it with: streamlit run quiz_app.py
import streamlit as st
st.title("Caribbean Capitals Quiz")
capitals = { # Module 5: a dictionary
"St. Vincent and the Grenadines": "Kingstown",
"Barbados": "Bridgetown",
"Saint Lucia": "Castries",
"Grenada": "St. George's",
}
choices = ["Bridgetown", "Castries", "Kingstown", "St. George's"] # Module 5: a list
score = 0 # Module 4: a counter
for country, capital in capitals.items(): # Module 5: .items()
answer = st.radio(f"What is the capital of {country}?", choices, index=None, key=country)
if answer == capital: # Module 3: if
score += 1
if st.button("Check my score"):
if score == len(capitals):
st.success(f"Perfect! {score} out of {len(capitals)}")
st.balloons()
elif score >= 2:
st.info(f"Good try: {score} out of {len(capitals)}")
else:
st.warning(f"{score} out of {len(capitals)} - have another go")See the browser: four questions, each with four choices.
Answer them all correctly and press Check my score:
Perfect! 4 out of 4 (green, with balloons)
Get 2 right: Good try: 2 out of 4 (blue)
Get 1 right: 1 out of 4 - have another go (yellow)Your mission today
Build your own app: a Robot Race Scoreboard that saves everyone's maze times and shows a leaderboard and chart.
Before you start: get your computer ready
Apps run on a computer, not on the robotics site. Ask a grown-up to help the first time.
- Install Python 3.12 from python.org (grown-up help).
- Open the Starter Kit folder and double-click
SETUP-Windows.bat. Wait until every line says OK. - To start an app, drag
race_app.pyontoRUN-APP-Windows.bat. Your browser opens it at http://127.0.0.1:8501.
The Robot Race Scoreboard
Run it with streamlit run race_app.py. The browser opens at http://127.0.0.1:8501.
# Module 7 - Robot Race Scoreboard app
# Run with: streamlit run race_app.py
import csv
import os
import streamlit as st
st.title("Robot Race Scoreboard")
callsign = st.text_input("Your callsign")
seconds = st.number_input("Maze time (seconds)", min_value=0.0, step=0.1)
if st.button("Save my time") and callsign:
with open("race.csv", "a", newline="") as f:
csv.writer(f).writerow([callsign, seconds])
st.success("Saved! Good driving, " + callsign)
st.balloons()
scores = []
if os.path.exists("race.csv"):
with open("race.csv") as f:
for name, time in csv.reader(f):
scores.append((float(time), name))
scores.sort()
st.header("Leaderboard")
for place, (time, name) in enumerate(scores, start=1):
st.write(str(place) + ". " + name + " - " + str(time) + " seconds")
if scores:
st.bar_chart({name: time for time, name in scores})Robot words
| Code | What it means |
|---|---|
| App | A program people use with buttons and boxes |
| Streamlit | Turns Python into an app in your browser |
st.button() | A button |
st.text_input() | A box to type in |
| race.csv | The file where the times are saved |
Challenges
Try one at a time. Change the code, run it, and watch.
Build puzzle
Put these app lines in order: title first, then the box, then the button.
if st.button("Save my time"):
st.title("Robot Race Scoreboard")
callsign = st.text_input("Your callsign")Show the answer
st.title("Robot Race Scoreboard")
callsign = st.text_input("Your callsign")
if st.button("Save my time"):Quiz 7
Pass with 3 out of 5. Then take it for points in the quiz section of robotics.a3tech.uk.